import React, {useCallback, useEffect, useMemo, useState} from 'react'

// antd about
import {
  Form,
  Input,
  InputNumber,
  Select,
  Button,
  Table,
  Tag,
  Space,
  Switch,
  Modal,
  message,
  Popconfirm,
  Image,
} from 'antd';

const { Option } = Select;

const { Column, ColumnGroup } = Table;

// 库存，销售，记录 的 axios
import {
  getInventories,
  getStocks,
} from '../../api/stock'

import { addRecordData } from '../../api/records'

import { generateUpdateDiscount } from '../../utils/generateRecord';

// redux
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { getStaffsUltimate, getStaffsLength } from '../../api/user';

export default function StaffsList() {

  // 获取跳转路由的 navigate
  const navigate = useNavigate()

  // 注册 补充数量 表单
  const [form] = Form.useForm()

  // 获取 redux 里的用户数据
  const username = useSelector((state) => state.user.info)

  // 页数
  const [pageOrder, setPageOrder] = useState(1)

  // 页数内容个数
  const [pageSize, setPageSize] = useState(3)

  // 商品数据 state
  const [goodsData, setGoodsData] = useState([])

  // 商品分类 state
  const [inventories, setInventories] = useState()

  // 商品总数
  const [total, setTotal] = useState(1)

  // 当前选择分类
  const [inventoryId, setInventoryId] = useState()

  // 当前查询内容
  const [name_like, setName_like] = useState()

  // 合并所有查询= 》
  const getGoodsList = useCallback(async({_page, _limit, inventoryId, name_like, operate}) => {
    // 包含了分页+类别+名字的查询
    const res = await getStaffsUltimate({_page, _limit, inventoryId, name_like})
    // 设置商品数据
    setGoodsData(res)
    // 设置页码
    setPageOrder(_page)
    // 设置当前页个数
    setPageSize(_limit)
    // 设置查询id
    setInventoryId(inventoryId)
    // 设置查询字符串
    setName_like(name_like)
    // 如果 operate 为重置
    if (operate === 'reset') {
      // 查询所有商品内容
      const all = await getStaffsLength()
      setTotal(all)
    } else {
      // 设置查询到的商品总数
      const Inquire = await getStaffsLength({inventoryId, name_like})
      setTotal(Inquire)
    }
  }, [])

  // 缓存商品分类 useEffect
  useEffect(() => {
    // 获取商品分类
    const Inventory = async() => {
      try {
        // try 语句块中放置可能会出现异常的代码
        let res = await getInventories()
        // 设置数据
        setInventories(res)
      } catch (error) {
        // catch 语句块中是出现异常后，解决异常问题的代码
        console.log('异常：', error)
      } finally {
        // finally 语句块是无论是否出现异常，最终都会执行的代码
      }
    }
    Inventory()

    // 获取商品数据
    const Stock = async() => {
      // 获取商品总数
      const res2 = await getStocks()
      setTotal(res2)

      getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId, name_like})
    }
    Stock()
  }, [])

  // 触发搜索
  const onFinish = useCallback((values) => {
    // 如果查询全部商品则不传递 inventoryId
    values.select === 7 ? values.select = undefined : values.select
    // 发送请求
    getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId: values.select, name_like: values.goodsName})
  }, [])

  // 触发重置
  const onReset = useCallback(() => {
    // 重置form
    form.resetFields()
    // 重置分页和查询数据
    setInventoryId(undefined)
    setName_like(undefined)
    setPageOrder(1)
    setPageSize(3)
    // 重新发送请求
    getGoodsList({_page: pageOrder, _limit: pageSize, inventoryId: undefined, name_like: undefined, operate: 'reset'})
  }, [])

  // 触发分页
  const pageSelect = useCallback(async(page, _pageSize) => {
    getGoodsList({_page: page, _limit: _pageSize, inventoryId, name_like})
  }, [])

  // 职位数组
  const [office, setOffice] = useState(['实习员工', '正式员工', '经理', '店长'])

  // 表格自定义渲染
  const columns = [
    {
      title: '员工照',
      dataIndex: 'image',
      key: 'image',
      render: (text) => (
        text
          ? <Image
            width={50}
            src={text}
          />
          : '暂无照片'
      ),
    },
    {
      title: '账户',
      dataIndex: 'username',
      key: 'username',
      render: (text) => (
        <span>{text}</span>
      ),
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
    },
    {
      title: '入职时间',
      dataIndex: 'jobStartDate',
      key: 'jobStartDate',
    },
    {
      title: '职位',
      dataIndex: 'permissions',
      key: 'permissions',
      render: (text) => (
        <span>{office[text]}</span>
      ),
    },
    {
      title: '操作',
      key: 'permissions',
      dataIndex: 'permissions',
      render: (text, record) => (
        <Space size="middle">
          <Button type='primary' onClick={() => {navigate('/staffs/staffInfo?id=' + record.id)}}>个人信息</Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      {/* 搜索 */}
      <Form
        form={form}
        name="horizontal_login"
        layout="inline"
        onFinish={onFinish}
      >
        <Form.Item
          name="select"
        >
          <Select
            style={{ width: 120 }}
            placeholder="请选择商品分类"
            options={inventories}
            fieldNames={{
              label: 'title',
              value: 'id',
            }}
          />
        </Form.Item>
        <Form.Item
          name="goodsName"
        >
          <Input
            placeholder="请输入查询商品名字"
          />
        </Form.Item>
        <Form.Item shouldUpdate>
          {() => (
            <Space size="middle">
              <Button
                type="primary"
                htmlType="submit"
              >
                查询
              </Button>
              <Button
                type="primary"
                onClick={onReset}
              >
              重置
              </Button>
            </Space>
          )}
        </Form.Item>
      </Form>

      {/* 表格 */}
      <Table
        dataSource={goodsData}
        columns={columns}
        rowKey='id'
        // rowSelection={{
        //   type: 'checkbox',
        // }}
        pagination={{
          position: ['topLeft'],
          pageSizeOptions: [1, 3, 5, 10],
          showSizeChanger: true,
          showQuickJumper: true,
          current: pageOrder,
          pageSize: pageSize,
          total,
          onChange: pageSelect,
        }}
      >
      </Table>
    </>
  )
}
